package com.whfc.fse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.DevicePlatform;
import com.whfc.common.third.zzkde.CrawlerData;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.MathUtil;
import com.whfc.fse.dao.FseCraneMapper;
import com.whfc.fse.dao.FseCrawlerMapper;
import com.whfc.fse.dao.FseGantryMapper;
import com.whfc.fse.dao.FseLiftMapper;
import com.whfc.fse.dto.*;
import com.whfc.fse.entity.FseCrane;
import com.whfc.fse.entity.FseCrawler;
import com.whfc.fse.entity.FseLift;
import com.whfc.fse.enums.FseType;
import com.whfc.fse.enums.FseWarnRuleType;
import com.whfc.fse.manager.FseGantryMgr;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;



import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author ：pyl
 * @date ：Created in 2022/6/1 11:43
 * @description：TODO
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class XxljobDemo {

    @Autowired
    private FseCraneMapper fseCraneMapper;

    @Autowired
    private FseLiftMapper fseLiftMapper;
    @Autowired
    private FseCrawlerMapper fseCrawlerMapper;

    @Autowired
    private FseGantryMapper fseGantryMapper;

    @Autowired
    private FseGantryMgr fseGantryMgr;

    @Autowired
    private AmqpTemplate amqpTemplate;


    @Test
    public void addCraneData(){
        FseWarnDTO fseWarnDTO = new FseWarnDTO();
        fseWarnDTO.setDeptId(16);
        fseWarnDTO.setCode("九磊智能001");
        fseWarnDTO.setFseType(FseType.CRANE);
        fseWarnDTO.setFseWarnRuleType(FseWarnRuleType.CRANE_UNKNOW_TYPE);
        fseWarnDTO.setTriggerTime(new Date());
        fseWarnDTO.setTriggerValue("报警了报警了======");
        fseWarnDTO.setTriggerObjectId(11);
        fseGantryMgr.addCrane(fseWarnDTO);
    }

    @Test
    public void generateDemoData() {
        String paramStr = "{\"craneIds\":[2],\"liftIds\":[1],\"crawlerIds\":[2]}";
        List<Date> times = new ArrayList<>();
        JSONObject param = JSONObject.parseObject(paramStr);
        if (param.containsKey("startTime") && param.containsKey("endTime")) {
            Date startTime = param.getDate("startTime");
            Date startDate = DateUtil.getDateBegin(startTime);
            Date endTime = param.getDate("endTime");
            Date endDate = DateUtil.getDateEnd(endTime);
            times = DateUtil.getDayListOfMinute(startDate, endDate, 60);
        } else {
            times.add(new Date());
        }
        // 获取塔机设备列表
        List<Integer> craneIds = param.getJSONArray("craneIds").toJavaList(Integer.class);
        List<FseCrane> fseCranes = fseCraneMapper.selectFseCraneListByCraneIds(craneIds);
        // 获取升降机设备列表
        List<Integer> liftIds = param.getJSONArray("liftIds").toJavaList(Integer.class);
        List<FseLift> fseLifts = fseLiftMapper.selectByLiftIds(liftIds);
        // 获取履带吊设备列表
        List<Integer> crawlerIds = param.getJSONArray("crawlerIds").toJavaList(Integer.class);
        List<FseCrawler> fseCrawlers = fseCrawlerMapper.selectBycrawlerIds(crawlerIds);
        for (Date time : times) {
            // 创建塔机数据
            for (FseCrane fseCrane : fseCranes) {
                Integer craneId = fseCrane.getId();
                try {
                    saveCrane(fseCrane, time);
                    saveCraneRecord(fseCrane, time);
                } catch (Exception e) {
                    e.printStackTrace();
                    XxlJobHelper.log("生成craneId:{} 塔吊演示数据失败 error:{}", craneId, e.getMessage());
                }
            }

            // 创建升降机数据
            for (FseLift fseLift : fseLifts) {
                Integer liftId = fseLift.getId();
                try {
                    if (StringUtils.isNotEmpty(fseLift.getLeftSn())) {
                        saveLiftData(fseLift.getLeftSn(), time);
                        fseLift.setLeftNetState(1);
                    }
                    if (StringUtils.isNotEmpty(fseLift.getRightSn())) {
                        saveLiftData(fseLift.getRightSn(), time);
                        fseLift.setRightNetState(1);
                    }
                    fseLiftMapper.updateByPrimaryKeySelective(fseLift);
                } catch (Exception e) {
                    e.printStackTrace();
                    XxlJobHelper.log("liftId:{} 升降机演示数据失败 error:{}", liftId, e.getMessage());
                }
            }
            // 创建履带吊数据
            for (FseCrawler fseLift : fseCrawlers) {
                Integer liftId = fseLift.getId();
                try {
                    if (StringUtils.isNotEmpty(fseLift.getSn())) {
                        saveCrawlerData(fseLift.getSn(), time);
                        fseLift.setNetState(1);
                    }

                    fseCrawlerMapper.updateByPrimaryKeySelective(fseLift);
                } catch (Exception e) {
                    e.printStackTrace();
                    XxlJobHelper.log("fseCrawlerId:{} 履带吊演示数据失败 error:{}", liftId, e.getMessage());
                }
            }
        }
    }

    public void saveCrane(FseCrane fseCrane, Date time) {
        FseCraneDataDTO fseCraneDeviceData = new FseCraneDataDTO();
        Random random = new Random();
        fseCraneDeviceData.setPlatform(DevicePlatform.yuke.name());
        fseCraneDeviceData.setSn(fseCrane.getSn());
        fseCraneDeviceData.setDipAngle(MathUtil.round(random.nextDouble(), 3));
        fseCraneDeviceData.setHeight(MathUtil.round(random.nextDouble() * 90, 1));
        fseCraneDeviceData.setRange(MathUtil.round(random.nextDouble() * 50, 1));
        fseCraneDeviceData.setTime(DateUtil.addSeconds(time, random.nextInt(60)));
        fseCraneDeviceData.setTurnAngle(MathUtil.round(random.nextDouble() * 350, 1));
        fseCraneDeviceData.setWeight(MathUtil.round(random.nextDouble() * 3, 3));
        fseCraneDeviceData.setWindSpeed(MathUtil.round(random.nextDouble() * 2, 1));
        fseCraneDeviceData.setMomentRatio(random.nextInt(100) / 100.0);

        fseCrane.setNetState(1);
        fseCraneMapper.updateByPrimaryKeySelective(fseCrane);
        Integer craneAlarmReason = random.nextInt(100);
        fseCraneDeviceData.setCraneStatus(parseYukeCraneValue(craneAlarmReason));
        // 发送队列处理
        amqpTemplate.convertAndSend(QueueConst.FSE_CRANE_REAL_DATA, JSON.toJSONString(fseCraneDeviceData));
    }

    public void saveCraneRecord(FseCrane fseCrane, Date time) {
        Random random = new Random();
        FseCraneRecordDTO craneRecordDTO = new FseCraneRecordDTO();
        craneRecordDTO.setPlatform(DevicePlatform.yuke.name());
        craneRecordDTO.setSn(fseCrane.getSn());
        craneRecordDTO.setStartTime(DateUtil.addSeconds(time, random.nextInt(60) * -1));
        craneRecordDTO.setEndTime(DateUtil.addSeconds(time, random.nextInt(300)));
        craneRecordDTO.setStartHeight(1.0 * random.nextInt(10));
        craneRecordDTO.setEndHeight(10 + 1.0 * random.nextInt(70));
        craneRecordDTO.setStartRange(MathUtil.round(random.nextDouble() * 60, 1));
        craneRecordDTO.setEndRange(MathUtil.round(random.nextDouble() * 60, 1));
        craneRecordDTO.setMaxWeight(MathUtil.round(random.nextDouble() * 3, 3));
        // 发送队列处理
        amqpTemplate.convertAndSend(QueueConst.FSE_CRANE_RECORD_DATA, JSON.toJSONString(craneRecordDTO));
    }

    private void saveLiftData(String sn, Date time) {
        FseLiftDataDTO fseLiftData = new FseLiftDataDTO();
        Random random = new Random();
        fseLiftData.setPlatform(DevicePlatform.yuke.name());
        fseLiftData.setSn(sn);
        fseLiftData.setTime(DateUtil.addSeconds(time, random.nextInt(60)));
        fseLiftData.setFloor(0);
        fseLiftData.setDipAngle(MathUtil.round(random.nextDouble(), 2));
        fseLiftData.setWeight(MathUtil.round(random.nextDouble(), 3));
        fseLiftData.setHeight(MathUtil.round(random.nextDouble() * 60, 1));
        fseLiftData.setPersonNo(random.nextInt(7));
        fseLiftData.setSpeed(MathUtil.round(random.nextDouble(), 1));
        fseLiftData.setWindSpeed(MathUtil.round(random.nextDouble(), 1));
        fseLiftData.setFrontDoorState(random.nextInt(2));
        fseLiftData.setBackDoorState(random.nextInt(2));
        int warnFlag = random.nextInt(100);
        fseLiftData.setLiftStatus(parseYukeLiftValue(warnFlag));
        // 发送队列处理
        amqpTemplate.convertAndSend(QueueConst.FSE_LIFT_REAL_DATA, JSON.toJSONString(fseLiftData));
        // 发送升降机运行记录
        saveLiftRecord(sn, time);

    }
    private void saveCrawlerData(String sn, Date time) {
        String s = "P*1*55*2*12313*1*2*18*5*41*3980*0*0*100*4218*0*4333*0*0*1750*0*0*0*0*0*0*1*5*3*1634291005*1634291009*0*0*0*0*0*0*0*1111*0*0*0*0*0*B*K;\n";
        JSONObject jsonObjectData = new JSONObject();
        JSONObject jsonObjectData2 = new JSONObject();
        jsonObjectData.put("src",s);
        jsonObjectData.put("time",time);
        jsonObjectData2.put("payload",jsonObjectData);
        // 发送队列处理
        amqpTemplate.convertAndSend(QueueConst.FSE_CRAWLER_CURRENT_DATA, jsonObjectData2.toJSONString());


    }

    private void saveLiftRecord(String sn, Date time) {
        Random random = new Random();
        double startHeight = MathUtil.round(random.nextDouble() * 60, 1);
        double endHeight = MathUtil.round(random.nextDouble() * 60, 1);
        FseLiftRecordDTO liftRecordDTO = new FseLiftRecordDTO();
        liftRecordDTO.setPlatform(DevicePlatform.yuke.name());
        liftRecordDTO.setSn(sn);
        liftRecordDTO.setStartTime(DateUtil.addSeconds(time, random.nextInt(60) * -1));
        liftRecordDTO.setEndTime(DateUtil.addSeconds(time, random.nextInt(300)));
        liftRecordDTO.setWeight(MathUtil.round(random.nextDouble(), 3));
        liftRecordDTO.setPersonNo(random.nextInt(7));
        liftRecordDTO.setStartHeight(startHeight);
        liftRecordDTO.setEndHeight(endHeight);
        liftRecordDTO.setStrokeHeight(MathUtil.round(Math.abs(endHeight - startHeight), 1));
        liftRecordDTO.setAvgSpeed(MathUtil.round(random.nextDouble(), 1));
        liftRecordDTO.setDirection(random.nextInt(3));
        liftRecordDTO.setDipAngleX(MathUtil.round(random.nextDouble() * 5, 3));
        liftRecordDTO.setDipAngleY(MathUtil.round(random.nextDouble() * 5, 3));
        // 推送数据
        amqpTemplate.convertAndSend(QueueConst.FSE_LIFT_RECORD_DATA, JSON.toJSONString(liftRecordDTO));
    }

    /**
     * 处理宇科塔机报警
     *
     * @param code 宇科报警编码
     * @return 风潮报警编码
     */
    private Integer parseYukeCraneValue(Integer code) {
        switch (code) {
            case 111:
            case 112:
            case 113:
            case 114:
                return FseWarnRuleType.CRANE_ANTI_COLLISION.value();
            case 12:
                return FseWarnRuleType.CRANE_WEIGHT.value();
            case 13:
                return FseWarnRuleType.CRANE_FORCE_MOMENT.value();
            case 14:
                return FseWarnRuleType.CRANE_TURN.value();
            case 15:
                return FseWarnRuleType.CRANE_WIND_SPEED.value();
            case 101:
                return FseWarnRuleType.CRANE_RANGE.value();
            case 102:
                return FseWarnRuleType.CRANE_HEIGHT_RANGE.value();
            case 103:
                return FseWarnRuleType.CRANE_ROTARY_LIMIT.value();
            default:
                return 0;
        }
    }

    /**
     * 处理宇科升降机报警
     *
     * @param code 宇科报警编码
     * @return 风潮报警编码
     */
    private Integer parseYukeLiftValue(Integer code) {
        switch (code) {
            case 1:
            case 4:
                return FseWarnRuleType.LIFT_WEIGH.value();
            case 2:
            case 3:
                return FseWarnRuleType.LIFT_SPEED.value();
            default:
                return 0;
        }
    }

    @Test
    public void syncAnSafeGantryRealData() {
        XxlJobHelper.log("安拾龙门吊实时数据同步");
        // 获取安拾平台龙门吊设备SN
        List<String> snList = fseGantryMapper.selectSnByPlatform(DevicePlatform.ansafe.name());
        if (snList.isEmpty()) {
            return;
        }
        for (String sn : snList) {
            Random random = new Random();
            try {
                FseGantryDataDTO gantryDataDTO = new FseGantryDataDTO();
                //数据转换
                gantryDataDTO.setPlatform(DevicePlatform.ansafe.name());
                gantryDataDTO.setSn(sn);
                gantryDataDTO.setTime(new Date());
                gantryDataDTO.setHeight(MathUtil.round(random.nextDouble()*10, 2));
                gantryDataDTO.setShift(MathUtil.round(random.nextDouble()*10, 2));
                gantryDataDTO.setWindSpeed(MathUtil.round(random.nextDouble()*10, 1));
                gantryDataDTO.setMainHookLiftHeight(MathUtil.round(random.nextDouble()*100, 1));
                gantryDataDTO.setSubHookLiftHeight(MathUtil.round(random.nextDouble()*100, 1));
                gantryDataDTO.setMainHookLiftWeight(MathUtil.round(random.nextDouble()*10, 1));
                gantryDataDTO.setSubHookLiftWeight(MathUtil.round(random.nextDouble()*10, 1));
                gantryDataDTO.setRigidLegShift(MathUtil.round(random.nextDouble() * 5, 2));
                gantryDataDTO.setSoftLegShift(MathUtil.round(random.nextDouble() * 15, 2));
                //主钩超载报警
                int mainHookWarn = 1;
//                if (1 == gantryWork.getMainoverloadwarn()) {
//                    mainHookWarn = 1;
//                }
                gantryDataDTO.setMainHookWarn(mainHookWarn);
                //副钩超载报警
                int subHookWarn = 1;

                gantryDataDTO.setSubHookWarn(subHookWarn);
                fseGantryMgr.addData(gantryDataDTO);
            } catch (Exception e) {
                XxlJobHelper.log("安拾龙门吊实时数据同步失败,sn:{}, error:{}", sn, e);
            }
        }
    }
}
